export class POPMenu {
  menuElement = null;
  constructor() {
    this.menuElement = document.createElement("div");
    this.menuElement.className = "POPMenu";
    // this.menuElement.style.display = "inline-block";
    this.menuElement.style.display = "none";
    document.body.appendChild(this.menuElement);
  }

  clear() {
    while (this.menuElement.firstChild) {
      this.menuElement.removeChild(this.menuElement.firstChild);
    }
  }

  /**
   *
   * @param {string} label
   * @param {*} attribute
   * @param {()=>void} callback
   */
  add(label, attribute = null, callback) {
    this.addItem(label, attribute, callback);
  }

  /**
   * @param {string} label 菜单标签
   * @param {object} attribute 菜单属性
   * @param {function} callback 菜单回调
   */
  addItem(label, attribute = null, callback = null) {
    const item = document.createElement("div");
    item.className = "POPMenuItem";
    item.textContent = label;
    item.onclick = () => {
      if (callback) {
        callback();
      }
      this.hide();
    };
    if (attribute) {
      for (const key in attribute) {
        item.setAttribute(key, attribute[key]);
      }
    }
    this.menuElement.appendChild(item);
  }

  onSelect(callback) {
    this.menuElement.addEventListener("click", (event) => {
      const target = event.target;
      if (target.classList.contains("POPMenuItem")) {
        const selectedItem = {
          label: target.textContent,
          attributes: {},
        };
        for (const attr of target.attributes) {
          selectedItem.attributes[attr.name] = attr.value;
        }
        callback(selectedItem);
      }
    });
  }

  hide() {
    this.menuElement.style.display = "none";
  }

  show(x, y) {
    this.menuElement.style.display = "block";
    // 确保菜单不会超出视口
    const menuRect = this.menuElement.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    if (x + menuRect.width > viewportWidth) {
      x = viewportWidth - menuRect.width;
    }
    if (y + menuRect.height > viewportHeight) {
      y = viewportHeight - menuRect.height;
    }

    this.menuElement.style.left = `${x}px`;
    this.menuElement.style.top = `${y}px`;
  }
}

/**
 * 获取全局的 POPMenu 实例。如果已经存在，则直接返回；如果不存在，则创建一个新的实例并存储在 window.POPMenuInstance 中。
 * @returns {POPMenu} 返回一个全局的 POPMenu 实例，如果已经存在则直接返回。如果没有创建过，则会创建一个新的实例并存储在 window.POPMenuInstance 中。
 */
export function POPMenuObject() {
  if (!window.POPMenuInstance) {
    window.POPMenuInstance = new POPMenu();
  }
  return window.POPMenuInstance;
}

export function POPMenuClose() {
  const popMenu = POPMenuObject();
  popMenu.hide();
}
